package com.chen10.gobang.common.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexUtils {

    // 正则表达式模式常量定义
    private static final String EMAIL_PATTERN =
        "\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}";
    private static final String PHONE_PATTERN =
        "^1[3456789]\\d{9}$";
    private static final String PASSWORD_PATTERN =
        "^(?=.*[0-9])(?=.*[a-zA-Z]).{6,20}$"; // 至少包含数字和字母，长度6到20
    private static final String URL_PATTERN =
        "^(https?|ftp)://[^\\s/$.?#].[^\\s]*$";
    private static final String IP_ADDRESS_PATTERN =
        "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";

    /**
     * 验证邮箱地址是否合法
     */
    public static boolean isValidEmail(String email) {
        Pattern pattern = Pattern.compile(EMAIL_PATTERN);
        if (email == null) return false;
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }

    /**
     * 验证电话号码是否合法（中国手机号）
     */
    public static boolean isValidPhone(String phone) {
        Pattern pattern = Pattern.compile(PHONE_PATTERN);
        if (phone == null) return false;
        Matcher matcher = pattern.matcher(phone);
        return matcher.matches();
    }

    /**
     * 验证密码是否符合要求
     */
    public static boolean isValidPassword(String password) {
        Pattern pattern = Pattern.compile(PASSWORD_PATTERN);
        if (password == null) return false;
        Matcher matcher = pattern.matcher(password);
        return matcher.matches();
    }

    /**
     * 验证URL格式是否正确
     */
    public static boolean isValidUrl(String url) {
        Pattern pattern = Pattern.compile(URL_PATTERN);
        if (url == null) return false;
        Matcher matcher = pattern.matcher(url);
        return matcher.matches();
    }

    /**
     * 验证IP地址是否合法（IPv4）
     */
    public static boolean isValidIpAddress(String ipAddress) {
        Pattern pattern = Pattern.compile(IP_ADDRESS_PATTERN);
        if (ipAddress == null) return false;
        Matcher matcher = pattern.matcher(ipAddress);
        return matcher.matches();
    }

    public static boolean isValidUsername(String username) {
        return username != null && username.length() >= 5 && username.length() <= 15;
    }
}
